package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsalgorithm.spec.fangkuai;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsalgorithm.spec.specConst;
import com.tc.dispatch.gsalgorithm.spec.taokong;
import com.tc.dispatch.gsalgorithm.spec.yuanzhu;
import com.tc.dispatch.gsservice.action.GSCalcAction;
import com.tc.dispatch.gsservice.action.GSCalcActionImp;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.filter.SimpleGSFilter;
import com.tc.dispatch.gsservice.filter.ZQXFilter;
import com.tc.dispatch.gsservice.model.DianDuPrice;
import com.tc.dispatch.gsservice.model.GSConstants;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.OtherConstants;
import com.tc.dispatch.gsservice.model.OutProcess;
import com.tc.dispatch.gsservice.model.ProcessFee;
import com.tc.dispatch.gsservice.model.SsignDensity;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.CacheSimModel;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.web.util.WidgtFactory;
import com.tc.dispatch.web.util.tools;
import com.tc.dispatch.web.util.cache.CacheManager;
import com.tc.dispatch.web.util.cache.CacheShell;
import com.tc.dispatch.web.util.cache.imp.ConstantsCacheShell;
import com.tc.dispatch.web.util.check.CheckValid;

public class orderSumSub extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderSumSub() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public boolean updateRecord(OrderSumSub oss) {

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			gss.updateOrderSumSub(oss);
		} catch (GSException gse) {
			System.out.println("updateRecord error :" + gse.getMessage());
			return false;
		}
		return true;
	}

	public int createOrderSumSub(OrderSumSub oss) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		int ret = 0;
		try {
			ret = gss.createOrderSumSub(oss);
		} catch (GSException gse) {
			System.out.println("createOrderSumSub error :" + gse.getMessage());
			return 0;
		}
		return ret;
	}

	public List getProcessSpec(String transnum, String processName, String map) {

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		// String ret;
		try {
			return gss.getProcessSpec(transnum, processName, map);
		} catch (GSException gse) {
			System.out.println("getProcessSpec error :" + gse.getMessage());
			return null;
		}
	}

	public Float getProcessYield(String processName, String map, String ssign,
			String spec, String plate, int month1, int year1, int factory,
			byte type) {

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float ret = new Float(0);

		try {
			if (type == 1)
				ret = gss.getYield(" where step='" + processName
						+ "' and map='" + map + "'", ssign, spec, plate,
						month1, year1, factory);
			else
				{
				if(processName.equals("切片")||processName.equals("前道磨加工"))
				{
					String sort=parse.parseSpec(spec).sort();
					String whereStr="";
					if(sort.equals(specConst.YuanZhu)||sort.equals(specConst.TaoKong))
						whereStr=" where name='"+processName+"默认成品率' and specType='"+specConst.YuanZhu+"'";
					else
						whereStr=" where name='"+processName+"默认成品率' and specType='"+specConst.Fangkuai+"'";
					System.out.println("defaultProcessYield:"+whereStr);
					ret=((OtherConstants)gss.findOtherConstants(whereStr).get(0)).getConstant();
				}
				else if(processName.equals("电镀"))
				{
					List sdList=gss.findSsignDensity(" where ssign='"+ssign+"'");
					String nameStr="";
					int high=0;
					if(sdList.size()>0)
						high=((SsignDensity)sdList.get(0)).getHigh();
					if(high==0)
						nameStr="低";
					else
						nameStr="高";
					plate=plate.toLowerCase();
					if(plate.indexOf("zn")>-1||plate.indexOf("锌")>-1)
					{
						nameStr+="ZN";
					}
					else
					{
						nameStr+="NI";
					}
					nameStr+="电镀默认成品率";
					System.out.println("电镀yield:"+nameStr);
					ret=((OtherConstants)gss.findOtherConstants(" where name='"+nameStr+"'").get(0)).getConstant();
				}
				else
				ret = ((OtherConstants) gss.findOtherConstants(
						" where name='" + processName + "默认成品率'").get(0))
						.getConstant();
				}
		} catch (GSException gse) {
			System.out.println("getProcessYield error :" + gse.getMessage());
			return ret;
		}
		return ret;
	}

	public Float getProcessArea(String before, String after, String processName) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float ret = new Float(0);
		try {
			spec before_spec = parse.parseSpec(before);
			spec after_spec = parse.parseSpec(after);
			System.out.println("before:"+before+":after:"+after+":processName:"+processName);
			ret = gss.getProcessArea(" where beforeType='" + before_spec.sort()
					+ "' and afterType='" + after_spec.sort()
					+ "' and processName='" + processName + "'", after_spec, before_spec);
		} catch (GSException gse) {
			System.out.println("getProcessArea error :" + gse.getMessage());
			return ret;
		}
		return ret;
	}

	public Float getProcessFee(String before, String after, String processName) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float ret = new Float(0);
		try {
			spec before_spec = parse.parseSpec(before);
			spec after_spec = parse.parseSpec(after);
			ProcessFee pf = gss.getProcessFee(" where specType='"
					+ after_spec.sort() + "' and processName='" + processName
					+ "'", after_spec);
			if (pf != null)
				ret = pf.getPrice();
		} catch (GSException gse) {
			System.out.println("getProcessFee error :" + gse.getMessage());
			return ret;
		}
		return ret;

	}

	public Float getDianDuFee(String plate) {

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float ret = new Float(0);
		try {

			List retList = gss.findDianDu(" where plate='" + plate + "'");
			if (retList.size() > 0)
				ret = ((DianDuPrice) retList.get(0)).getPrice();
		} catch (GSException gse) {
			System.out.println("getProcessFee error :" + gse.getMessage());
			return ret;
		}
		return ret;
	}

	public String getQieNum(String before, String after, String processName,int year1,int month1) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		String ret = "1";
		
			spec before_spec = parse.parseSpec(before);
			spec after_spec = parse.parseSpec(after);
			CacheManager cm = CacheManager.getInstance();
			try {
			CacheShell cs = cm.getCacheShell(cm.OTHERCONSTANTS_CACHE);
			System.out.println("get cs sucess");
			OtherConstants oc = (OtherConstants) cs.getValue(ConstantsCacheShell.ZeroQueXian);
			System.out.println("oc.getConstants"+oc.getConstant());
			OutProcess op;
			if(processName.equals("切片"))
				op= gss.getKnife(after_spec.sort(), after_spec,new ZQXFilter(after,year1,month1,oc.getConstant(),new Float(0)));
			else
				op = gss.getKnife(after_spec.sort(), after_spec,new SimpleGSFilter());
			GSCalcAction gsca = gss.getGSCalc();
			fangkuai rem=new fangkuai();
			int num = gsca.gsQieNum(before_spec, after_spec, rem,processName, op
					.getKnIn(), op.getKnOut()).intValue();
			System.out.println("num is:"+num+":"+op.getKnIn()+":"+op.getKnOut());
			if(before_spec.sort().equals(specConst.Fangkuai)&&after_spec.sort().equals(specConst.Fangkuai))
			{
				if(num>1)
				{
					System.out.println("rem is:"+rem.getspec());
					ret=num+"_"+rem.getspec();
				}
			}
			else
				ret=String.valueOf(num);
		} catch (GSException gse) {
			System.out.println("getQieNum error :" + gse.getMessage());
			return ret;
		} catch (Exception e) {
			System.out.println("unCatched error:" + e.getMessage());
			return ret;
		}
		return ret;

	}
	

	public Float getHopeGrossWeight(String ssign, String spec) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float ret = new Float(0);
		try {

			List retList = gss.findSsignDensity(" where ssign='" + ssign + "'");
			if (retList.size() > 0)
				ret = ((SsignDensity) retList.get(0)).getDensity();
			spec m_spec = parse.parseSpec(spec);

			ret = new Float(m_spec.volume() * ret.floatValue() / 1000 / 1000);
			Float qian = gss.getDefaultCheck(" where spec='" + m_spec.sort()
					+ "' and name='" + GSConstants.DEFUALT_CHECK_QIANDAO_YIELD
					+ "'", spec);
			if (qian.floatValue() > 0)
				ret = new Float(ret.floatValue() / qian.floatValue());
		} catch (GSException gse) {
			System.out.println("getHopeGrossWeight error :" + gse.getMessage());
			return ret;
		}
		return ret;

	}

	public List findOrderSumSubs(String id, String type) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			return gss.findOrderSumSub(" where orderSumId=" + id + " and type="
					+ type+" order by processPos");
		} catch (GSException e) {
			System.out.println("findOrderSumSubs:" + e.getMessage());
			return null;
		}
	}

	public boolean removeRecord(int id) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		try {
			gss.removeOrderSumSub(id);
		} catch (GSException gse) {
			System.out.println("removeRecord error :" + gse.getMessage());
			return false;
		}
		return true;

	}

	public Float getDensity(String ssign) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		Float density = new Float(0);
		try {
			List ret = gss.findSsignDensity(" where ssign='" + ssign + "'");

			if (ret.size() > 0)
				density = ((SsignDensity) ret.get(0)).getDensity();
		} catch (GSException gse) {
			System.out.println("getDesity error :" + gse.getMessage());
			return density;
		}
		return density;

	}

	public String getXinZiSpec(String spec_yz, String spec) {
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		String ret = "";
		try {
			if (parse.parseSpec(spec).sort().equals(specConst.TaoKong)) {
				Float value = gss.getDefaultCheck(
						" where spec='taokong' and name='芯子'", spec);
				taokong m_spec = (taokong) parse.parseSpec(spec);
				yuanzhu m_spec_yz = (yuanzhu) parse.parseSpec(spec_yz);
				value = new Float(m_spec.getInDiameter() - value.floatValue());
				System.out.println(m_spec.getInDiameter() + ":" + value);
				return "$" + tools.myDecimalFormat(value.doubleValue(), 2)
						+ "*" + m_spec_yz.getHeight();
			} else
				return ret;

		} catch (GSException gse) {
			System.out.println("getDesity error :" + gse.getMessage());
			return ret;
		} catch (Exception e) {

			System.out.println("exception found:" + e.getMessage());
			return ret;
		}

	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to
	 * post.
	 *
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		GSServiceLocal gss = gsHelper.getGSServiceLocal();

		CheckValid rcv = WidgtFactory.getRequestCheckValid(request);
		CheckValid scv = WidgtFactory.getSimpleCheckValid();
		String action = (String) rcv.checkString("action");
		if (action.equals("list")) {
			String ordersumid = (String) rcv.checkString("orderSumId");
			String type = (String) rcv.checkString("type");
			try {
				List ret = new ArrayList();
				if (!type.equals(""))
					ret = gss.findOrderSumSub(" where orderSumId=" + ordersumid
							+ " and type=" + type + " order by processPos");
				else
					ret = gss.findOrderSumSub(" where orderSumId=" + ordersumid
							+ " order by processPos");
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);
				response.getWriter().print(json);
			} catch (GSException e) {
				response.sendRedirect("orderError.jsp?error="
						+ e.getErrorCode());
			}
		} else if (action.equals("new")) {
			Integer id = (Integer) scv.checkInteger("id");
			try {
				Integer orderSumId = (Integer) rcv.checkInteger("orderSumId");
				String processName = (String) rcv.checkString("processName");
				String afterSpec = (String) rcv.checkString("afterSpec");
				Float processYield = (Float) rcv.checkFloat("processYield");
				Float processUpdate = (Float) rcv.checkFloat("processUpdate");
				Float unitPrice = (Float) rcv.checkFloat("unitPrice");
				Float processArea = (Float) rcv.checkFloat("processArea");
				Float processPrice = (Float) rcv.checkFloat("processPrice");
				Float untilPrice = (Float) rcv.checkFloat("untilPrice");
				byte type = Byte.parseByte(request.getParameter("type"));
				Integer processNum = (Integer) rcv.checkInteger("processNum");
				Integer processPos = (Integer) rcv.checkInteger("processPos");
				Float otherFee = (Float) rcv.checkFloat("otherFee");
				String updateStr = (String) rcv.checkString("updateStr");
				OrderSumSub osm = new OrderSumSub(id, orderSumId, processName,
						"", afterSpec, processYield, processUpdate, unitPrice,
						processNum, processArea, processPrice, processPos,
						otherFee, untilPrice, type,updateStr);
				gss.createOrderSumSub(osm);
			} catch (NumberFormatException nfe) {
				System.out.print("numberfomat error!:" + nfe.getMessage());
			} catch (GSException gse) {
				response.sendRedirect("orderError.jsp?error="
						+ gse.getErrorCode());
			}
			response.getWriter().print("{success:true}");

		} else if (action.equals("update")) {

			try {
				Integer id = (Integer) rcv.checkInteger("id");
				Integer orderSumId = (Integer) rcv.checkInteger("orderSumId");
				String processName = (String) rcv.checkString("processName");
				String afterSpec = (String) rcv.checkString("afterSpec");
				Float processYield = (Float) rcv.checkFloat("processYield");
				Float processUpdate = (Float) rcv.checkFloat("processUpdate");
				Float unitPrice = (Float) rcv.checkFloat("unitPrice");
				Float processArea = (Float) rcv.checkFloat("processArea");
				Float processPrice = (Float) rcv.checkFloat("processPrice");
				Float untilPrice = (Float) rcv.checkFloat("untilPrice");
				byte type = Byte.parseByte(request.getParameter("type"));
				Integer processNum = (Integer) rcv.checkInteger("processNum");
				Integer processPos = (Integer) rcv.checkInteger("processPos");
				Float otherFee = (Float) rcv.checkFloat("otherFee");
				String updateStr = (String) rcv.checkString("updateStr");
				OrderSumSub osm = new OrderSumSub(id, orderSumId, processName,
						"", afterSpec, processYield, processUpdate, unitPrice,
						processNum, processArea, processPrice, processPos,
						otherFee, untilPrice, type,updateStr);
				gss.updateOrderSumSub(osm);
			} catch (NumberFormatException nfe) {
				System.out.print("numberfomat error!:" + nfe.getMessage());
			} catch (GSException gse) {
				response.sendRedirect("orderError.jsp?error="
						+ gse.getErrorCode());
			}
			response.getWriter().print("{success:true}");

		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
